package zhongbo.java.air.monitor.web.websocket;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年04月09日 星期三 23:02:33
 */
@ServerEndpoint(value = "/websocket/alert")
@Component
@Slf4j
public class AlertLogWebSocket {

    // session缓存
    public final static Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void openConn(Session session) {
        String sessionId = session.getId();
        System.out.println("建立ws连接: " + sessionId);

        sessionMap.put(sessionId, session);
    }

    /**
     * 向ws chat客户端发送错误消息,并且断开连接
     *
     * @param session session会话
     * @param msg     错误消息
     */
    private void doClose(Session session, String msg) {
        try {
            if (StrUtil.isNotBlank(msg)) {
                sendMessage(session, msg);
            }
            session.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送文本消息
     *
     * @param session ws会话对象
     * @param msg     消息文本
     */
    public static void sendMessage(Session session, String msg) {
        String sessionId = session.getId();
        log.info("向: {} 发送ws消息: {}", sessionId, msg);
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            log.error("给 ws 客户端: {} 发送消息失败", session.getId(), e);
        }
    }

    /**
     * 发送文本消息
     *
     * @param msg 消息文本
     */
    public static void sendMessageToAll(String msg) {
        List<Session> sessions = new ArrayList<>(sessionMap.values());
        log.info("广播ws消息: {}", msg);
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                log.error("给 ws 客户端: {} 发送消息失败", session.getId(), e);
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        String closeMsg = String.format("关闭ws连接: %s, reason: %s", sessionId, reasonPhrase);
        log.info(closeMsg);
        sessionMap.remove(sessionId);
    }

    @OnMessage
    public void echoTextMessage(Session session, String msg, boolean last) {
        if (session.isOpen()) {
            log.info("收到ws消息: {}, last: {}", msg, last);

        }
    }
    /*
    html 客户端代码:
    var wsClient = new WebSocket('ws://localhost:8080/chat1/zhangsan/99999')
    wsClient.send('你好吗?')
    wsClient.close()
     */

}
